using System.Security.Claims;

namespace MESData.ProductionPlan.API.Extensions
{
    /// <summary>
    /// ClaimsPrincipal扩展方法
    /// </summary>
    public static class ClaimsPrincipalExtensions
    {
        /// <summary>
        /// 获取当前用户ID
        /// </summary>
        public static int GetUserId(this ClaimsPrincipal principal)
        {
            var userIdClaim = principal.FindFirst(ClaimTypes.NameIdentifier);
            return userIdClaim != null && int.TryParse(userIdClaim.Value, out var userId) ? userId : 0;
        }

        /// <summary>
        /// 获取当前用户账号
        /// </summary>
        public static string GetUserAccount(this ClaimsPrincipal principal)
        {
            return principal.FindFirst(ClaimTypes.Name)?.Value ?? string.Empty;
        }

        /// <summary>
        /// 获取当前用户角色
        /// </summary>
        public static string GetUserRole(this ClaimsPrincipal principal)
        {
            return principal.FindFirst(ClaimTypes.Role)?.Value ?? string.Empty;
        }

        /// <summary>
        /// 获取当前用户姓名（如果有的话）
        /// </summary>
        public static string GetUserName(this ClaimsPrincipal principal)
        {
            return principal.FindFirst("Name")?.Value ?? principal.GetUserAccount();
        }

        /// <summary>
        /// 检查用户是否已认证
        /// </summary>
        public static bool IsAuthenticated(this ClaimsPrincipal principal)
        {
            return principal.Identity?.IsAuthenticated == true;
        }
    }
} 